package com.iring.config;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.iring.domain.config.PayConfig;
import com.iring.domain.config.prop.VOSCustomerProperties;
import com.iring.dao.common.PayOrderDao;
import com.iring.dao.vos.PayReturnDao;
import com.iring.domain.common.AmountTask;
import com.iring.domain.common.PayOrder;
import com.iring.domain.common.User;
import com.iring.domain.pay.check.AlipayCheck;
import com.iring.domain.pay.check.PaypalCheck;
import com.iring.domain.pay.info.AliPayInfo;
import com.iring.domain.pay.info.PayPalInfo;
import com.iring.domain.pay.res.AliPayRes;
import com.iring.domain.pay.res.PaypalRes;
import com.iring.domain.vos.pay.PayReturn;
import com.iring.domain.vos.pay.VosPay;
import com.iring.service.common.AllSuiteService;
import com.iring.service.common.OrderService;
import com.iring.service.common.PayAmountService;
import com.iring.service.common.UserService;
import com.iring.service.pay.PayService;
import com.iring.service.sms.MessageService;

/**
 * 每晚定时任务进行处理
 * 包括所有套餐获取和异常订单处理
 *
 * @author wanggan
 */
@Component
public class PackageTimeSchedule {

    private static final Logger logger = LoggerFactory.getLogger(PackageTimeSchedule.class);

    @Autowired
    PayAmountService payAmountService;

    @Autowired
    UserService userService;

    @Autowired
    VOSCustomerProperties vosCustomerProperties;

    @Autowired
    MessageService messageService;

    @Autowired
    AllSuiteService allSuiteService;

    @Autowired
    PayReturnDao payDao;

    @Autowired
    PayOrderDao payOrderDao;

    @Autowired
    OrderService orderService;

    @Resource(name = "paypal")
    PayService<PayPalInfo, PaypalRes,PaypalCheck> paypalService;

    @Resource(name = "alipay")
    PayService<AliPayInfo,AliPayRes,AlipayCheck> alipayService;


    // 服务器启动就拉取套餐,并且在24小时后重新请求,设置每天12.00执行任务
    @Scheduled(cron = "${com.zycoo.local.schduleCorn}")
    public void freshAllSuiteAndDealLogAndCdr() {
        allSuiteService.cleanAllSuite();
        allSuiteService.loadAllSuite();
        logger.info("0 at every night,refresh all suite from vos");

        //查询所有的异常订单
        List<AmountTask> list = payAmountService.finAllExceptionUndealTask();

        // 如果查出的记录为空,则不继续下面的订单异常处理了
        if (list.size() == 0) {
            return;
        }
        for (AmountTask amountTask : list) {
            Boolean ispay = dealVosExpOrder(amountTask);
            if(!ispay){
                //更新订单信息，包括异常订单和订单记录
                // 如果异常订单没有处理成功,则循环五次进行
                for (int i = 0; i < 5; i++) {
                    ispay = dealVosExpOrder(amountTask);
                    if (ispay) {
                        break;
                    }
                }
            }
        }
    }

    @Scheduled(cron = "${com.zycoo.local.msgCorn}")
    public void sendToRestAmountsLessThanLimit() {
        List<User> list = userService.findUserByRestAmountsLessThanLimit();
        logger.info("send sms balance restAmounts alarm notice");
        for (int i = 0; i < list.size(); i++) {
            // 循环发送消息
            messageService.sendMsg(list.get(i).getContactPhonenum());
        }
    }

    @Scheduled(initialDelayString = "${com.zycoo.local.orderInitDelay}",fixedDelayString = "${com.zycoo.local.orderDelay}")
    public void OrderPaySchedule(){
        logger.info("deal with pay plateform order");
        List<String> payList = new ArrayList<>();
        //paypal
        payList.add(PayConfig.ORDER_CREATED);
        payList.add(PayConfig.ORDER_APPROVED);
        //alipay
        payList.add(PayConfig.WAIT_BUYER_PAY);


        List<String> oList = new ArrayList<>();
        oList.add(PayConfig.WAIT_USER_PAY);
        oList.add(PayConfig.SYSTEM_PROCESSING);

        List<PayOrder> orderList = payOrderDao.findByPayStatusInAndOrderStatusIn(payList,oList);
        if(orderList.size()==0){
            return;
        }
        for(PayOrder payOrder:orderList){
            String orderStatus = payOrder.getOrderStatus();
            String orderid = payOrder.getOrderId();
            synchronized (orderStatus) {
                if(PayConfig.SYSTEM_PROCESSING.equalsIgnoreCase(orderStatus)){
                    //TODO 如果是订单正在处理中，对vos发起充值
                    String paystatus = payOrder.getPayStatus();
                    String payerid = payOrder.getPayerId();
                    String tradeNo = payOrder.getTradeNo();
                    orderService.updateByOrderid(orderid,tradeNo, paystatus, payerid);
                }else {
                    //TODO如果是等待用户付款的话，则去相应的平台进行查询
                    //如果是paypal的话，请求paypal
                    String orderType = payOrder.getOrderType();

                    if (PayConfig.PAYPAL.equals(orderType)) {
                        PaypalCheck paypalCheck = new PaypalCheck();
                        String tradeNo = payOrder.getTradeNo();
                        paypalCheck.setTradeNo(tradeNo);
                        paypalCheck.setOrderId(orderid);

                        paypalCheck = paypalService.checkPay(paypalCheck);

                        if (paypalCheck.getPayResult()) {
                            String paystatus = paypalCheck.getPayStatus();
                            String payerid = paypalCheck.getPayerId();
                            orderService.updateByOrderid(orderid,tradeNo, paystatus, payerid);
                        }
                    } else if (PayConfig.ALIPAY.equals(orderType)) {
                        AlipayCheck alipayCheck = new AlipayCheck();
                        alipayCheck.setOrderId(orderid);
                        alipayCheck = alipayService.checkPay(alipayCheck);
                        if (alipayCheck.getPayResult()) {
                            String paystatus = alipayCheck.getPayStatus();
                            String payerid = alipayCheck.getPayerId();
                            String tradeNo = alipayCheck.getTradeNo();
                            orderService.updateByOrderid(orderid,tradeNo, paystatus, payerid);
                        }
                    }
                }
            }
        }
    }

    /**
     * 上传vos进行充值或者核算业务,处理异常订单
     *
     * @param amountTask
     *            {@link AmountTask}
     * @return 充值结果
     */
    public Boolean dealVosExpOrder(AmountTask amountTask) {
        VosPay vosPay = new VosPay(amountTask.getUsername(), vosCustomerProperties.getOwnerType(),
                amountTask.getOptamounts(), "异常订单充值处理");
        Object object = payDao.createVosPay(vosPay);
        if (object instanceof PayReturn) {
            PayReturn payReturn = (PayReturn) object;
            if (payReturn.getInfoPay().getPayMoney().compareTo(amountTask.getOptamounts()) == 0) {
                payAmountService.updateExceptionOrderStutus(amountTask.getOrderid());
                logger.info("update exception order success={}", amountTask);
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }
}
